//
//  SSSForgetPasswordViewController.m
//  SSSMerchant
//
//  Created by Darker on 2017/3/31.
//  Copyright © 2017年 xnxin. All rights reserved.
//

#import "SSSForgetPasswordViewController.h"
#import "ZDMyTextField.h"

@interface SSSForgetPasswordViewController ()<UITextFieldDelegate>
{
    
    BOOL move;//记录文本框是否移动
    UIButton *_registerBtn;//注册按钮
    //NSTimer *timer;
    UIButton *button;
}
/**
 *  装文本框的数组
 */
@property (nonatomic,strong)  NSMutableArray <ZDMyTextField *> *textFiledArray;
/** 发送验证码按钮; */
@property (nonatomic, strong)UIButton *sendAuthCodeBtn;


@end

@implementation SSSForgetPasswordViewController

- (void)viewWillAppear:(BOOL)animated{
    
    [super viewWillAppear:animated];
    self.navigationController.navigationBar.hidden = NO;
    //设置导航栏背景图片为一个空的image，这样就透明了
    //[self.navigationController.navigationBar setBackgroundImage:[[UIImage alloc] init] forBarMetrics:UIBarMetricsDefault];
    self.title = @"忘记密码";
    //[self.navigationController.navigationBar setBackgroundColor:[UIColor colorWithHex:@"000000"]];
    
    //去掉透明后导航栏下边的黑边
    [self.navigationController.navigationBar setShadowImage:[[UIImage alloc] init]];
    
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    //常见UI
    [self setUpUI];
    
}
- (void)setUpUI{
    
    UIButton *leftNavBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    leftNavBtn.bounds = CGRectMake(0, 0, WidthIos6CompeteWithCurrent(8), HeigthIos6CompeteWithCurrent(16));
    [leftNavBtn setBackgroundImage:[UIImage imageNamed:@"icon_arrow_left"] forState:UIControlStateNormal];
    leftNavBtn.titleLabel.font = [SSSFont systemFontOfSize:12];
    UIBarButtonItem *rightBarButton = [[UIBarButtonItem alloc]initWithCustomView:leftNavBtn];
    [leftNavBtn addTarget:self action:@selector(backBtn) forControlEvents:UIControlEventTouchDown];
    self.navigationItem.leftBarButtonItem = rightBarButton;
    
    
    UIImageView *bgImageView = [[UIImageView alloc]initWithFrame:self.view.bounds];
    bgImageView.userInteractionEnabled = YES;
    bgImageView.image = [UIImage imageNamed:@"bg"];
    [self.view addSubview:bgImageView];
    
    // 设置五个文本框
    // 占位文字的数组
    NSArray *placeHolders = @[@"输入手机号",@"请输入验证码",@"输入新密码",@"请确认新密码密码"];
    // 装图片名字的数组
    NSArray *imageNamesArray = @[@"img_phone",@"icon_auth-code",@"img_password",@"img_password"];
    
    //发送验证码按钮
    _sendAuthCodeBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [_sendAuthCodeBtn setTitle:@"发送验证码" forState:UIControlStateNormal];
    [_sendAuthCodeBtn setBackgroundColor:[UIColor colorWithHex:@"46B77D"]];
    //_sendAuthCodeBtn.buttonType = UIButtonTypeCustom;
    [bgImageView addSubview:_sendAuthCodeBtn];
    _sendAuthCodeBtn.titleLabel.font = [SSSFont systemFontOfSize:14];
    _sendAuthCodeBtn.layer.borderColor = [[UIColor whiteColor] colorWithAlphaComponent:0.7].CGColor;
    _sendAuthCodeBtn.layer.borderWidth = 1;
    _sendAuthCodeBtn.layer.cornerRadius = 8;
    _sendAuthCodeBtn.layer.masksToBounds = YES;
    [_sendAuthCodeBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [_sendAuthCodeBtn addTarget:self action:@selector(sendAuthCodeClick) forControlEvents:UIControlEventTouchDown];
    
    // 设置一个指针，指向文本框
    UITextField *currentFiled = nil;
    //添加文本框
    for (int index = 0; index < placeHolders.count; index++) {
        
        ZDMyTextField *textField = [[ZDMyTextField alloc]init];
        [self.textFiledArray addObject:textField];
        textField.returnKeyType = UIReturnKeyDone;
        textField.delegate = self;
        textField.tag = 200 +index;
        textField.font = [SSSFont systemFontOfSize:14];
        [bgImageView addSubview:textField];
        textField.placeholder = placeHolders[index];
        textField.textColor = [UIColor colorWithHex:@"000000"];
        textField.layer.borderWidth = 0.5;
        textField.layer.borderColor = [UIColor colorWithHex:@"40B87B"].CGColor;
        textField.layer.cornerRadius = HeigthIos6CompeteWithCurrent(10);
        textField.layer.masksToBounds = YES;
        // 设置文本框的清楚按钮的模式
        textField.clearButtonMode = UITextFieldViewModeWhileEditing;
        // 设置文本框的清楚按钮的模式
        textField.clearsOnBeginEditing = YES;
        // 设置文本框的光标颜色
        textField.tintColor = [UIColor colorWithHex:@"44b034"];
        // [self setLfetView:imageNamesArray[index] isLeft:YES textField:textField];
        [self setLfetImageView:imageNamesArray[index] isLeft:YES textField:textField];
        
        //布局约束
        //ZD_WEAKSELF;
        [textField mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(bgImageView).offset(WidthIos6CompeteWithCurrent(43));
            
            if (textField.tag == 201) {
                make.right.equalTo(bgImageView).offset(WidthIos6CompeteWithCurrent(-163));
                
                //发送验证码按钮布局约束
                _sendAuthCodeBtn.sd_layout
                .topEqualToView(textField)
                .bottomEqualToView(textField)
                .rightSpaceToView(bgImageView,WidthIos6CompeteWithCurrent(40))
                .leftSpaceToView(textField,WidthIos6CompeteWithCurrent(15));
                
            }else{
                
                make.right.equalTo(bgImageView).offset(WidthIos6CompeteWithCurrent(-43));
            }
            make.height.equalTo(@(HeigthIos6CompeteWithCurrent(51)));
            if (currentFiled == nil) {
                make.top.equalTo(bgImageView).offset(HeigthIos6CompeteWithCurrent(145));
            }
            else {
                make.top.equalTo(currentFiled.mas_bottom).offset(HeigthIos6CompeteWithCurrent(15));
            }
        }];
        currentFiled = textField;
        if (index == 0 || index == 1) {
            textField.keyboardType = UIKeyboardTypePhonePad;
        }else if (index == 2) {
            textField.secureTextEntry = YES;
        }else if (index == 3){
            textField.secureTextEntry = YES;
        }
        
    }
    
    //添加注册按钮
    _registerBtn = [[UIButton alloc]init];
    [_registerBtn setTitle:@"提交" forState:UIControlStateNormal];
    _registerBtn.titleLabel.font = [SSSFont systemFontOfSize:16];
    [_registerBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [_registerBtn setBackgroundColor:[UIColor colorWithHex:@"40B87B"]];
    _registerBtn.layer.cornerRadius = 10;
    _registerBtn.layer.masksToBounds = YES;
    [_registerBtn addTarget:self action:@selector(registerBtnClick) forControlEvents:UIControlEventTouchDown];
    [bgImageView addSubview:_registerBtn];
    
    //添加布局约束
    _registerBtn.sd_layout
    .topSpaceToView(currentFiled,HeigthIos6CompeteWithCurrent(30))
    .leftEqualToView(currentFiled)
    .rightEqualToView(currentFiled)
    .heightIs(HeigthIos6CompeteWithCurrent(44));
}
#pragma mark - 发送验证码按钮
- (void)sendAuthCodeClick{
    
    // 让所有的文本框放弃第一响应者
    [self doResignFirstResponder];
    
    if ([_textFiledArray[0].text isEqualToString:@""]) {
        
        [QMUITips showError:@"请输入手机号" inView:self.view hideAfterDelay:2];
    }else{
        
        //发送验证码
        [self sendCode];
    }

    
//    NSString *sendCodeUrl = [NSString stringWithFormat:@"%@%@%@%@",SSSCommomUrl,@"user/",_textFiledArray[0].text,@"/getCode"];
//    
//    NSMutableDictionary *params = [NSMutableDictionary dictionary];
//    params[@"phone"] = simple.userModel.phone;
//    
//    [ZDNetManager zd_requestWithType:ZDHttpRequestTypeGet UrlString:sendCodeUrl Parameters:params SuccessBlock:^(id response) {
//        
//        
//        if ([response[@"sataus"] intValue] == 0) {
//            
//            //倒计时
//            [self verificationCodeOfTimer];
//            [QMUITips showSucceed:@"获取验证码成功" inView:self.view hideAfterDelay:2];
//            
//        }else{
//            
//            [QMUITips showError:response[@"message"] inView:self.view hideAfterDelay:2];
//            return ;
//        }
//        
//    } FailureBlock:^(NSError *error) {
//        
//        [QMUITips showError:error.localizedDescription inView:self.view hideAfterDelay:2];
//        
//    } progress:^(int64_t bytesProgress, int64_t totalBytesProgress) {
//        
//        
//    }];
    //发送验证码
    //[self verificationCodeOfTimer];
    //timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(colockCome:) userInfo:nil repeats:YES];
}
#pragma mark - 倒计时开始
- (void)verificationCodeOfTimer
{
    __block int timeout = 60.0; //倒计时时间
    ZD_WEAKSELF;
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    dispatch_source_t _timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0,queue);
    dispatch_source_set_timer(_timer,dispatch_walltime(NULL, 0),1.0*NSEC_PER_SEC, 0); //每秒执行
    dispatch_source_set_event_handler(_timer, ^{
        if(timeout<=0){ //倒计时结束，关闭
            dispatch_source_cancel(_timer);
            dispatch_async(dispatch_get_main_queue(), ^{
                //设置界面的按钮显示 根据自己需求设置
                [weakSelf.sendAuthCodeBtn setTitle:@"发送验证码" forState:UIControlStateNormal];
                weakSelf.sendAuthCodeBtn.userInteractionEnabled = YES;
                weakSelf.sendAuthCodeBtn.enabled = YES;
                [weakSelf.sendAuthCodeBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
                weakSelf.sendAuthCodeBtn.layer.borderColor = [[UIColor whiteColor] colorWithAlphaComponent:0.7].CGColor;
                [weakSelf.sendAuthCodeBtn setBackgroundColor:[UIColor colorWithHex:@"46B77D"]];
                weakSelf.sendAuthCodeBtn.layer.borderWidth = 1;
            });
            
        }else{
            int seconds = (timeout-1) % 60;
            NSString *strTime = [NSString stringWithFormat:@"%.2d", seconds];
            dispatch_async(dispatch_get_main_queue(), ^{
                //设置界面的按钮显示 根据自己需求设置
                //NSLog(@"____%@",strTime);
                [UIView beginAnimations:nil context:nil];
                [UIView setAnimationDuration:1];
                //                NSMutableAttributedString *AttributedStr = [[NSMutableAttributedString alloc]initWithString:str];
                //                //                [AttributedStr addAttribute:NSFontAttributeName
                //                //
                //                //                                      value:[UIFont systemFontOfSize:16.0]
                //                //
                //                //                                      range:NSMakeRange(0, 2)];
                //
                //                [AttributedStr addAttribute:NSForegroundColorAttributeName
                //
                //                                      value:[UIColor redColor]
                //
                //                                      range:NSMakeRange(0, 2)];
                //                //                [AttributedStr addAttribute:NSForegroundColorAttributeName
                //                //
                //                //                                      value:[UIColor grayColor]
                //                //
                //                //                                      range:NSMakeRange(2,6)];
                //
                
                [weakSelf.sendAuthCodeBtn setTitle:[NSString stringWithFormat:@"%@秒后重发",strTime] forState:UIControlStateNormal];
                [weakSelf.sendAuthCodeBtn setTitleColor:[UIColor colorWithHex:@"BBBBBB"]forState:UIControlStateNormal];
                weakSelf.sendAuthCodeBtn.layer.borderColor = [[UIColor grayColor] colorWithAlphaComponent:0.2].CGColor;
                weakSelf.sendAuthCodeBtn.layer.borderWidth = 0.5;

                [UIView commitAnimations];
                weakSelf.sendAuthCodeBtn.userInteractionEnabled = NO;
                weakSelf.sendAuthCodeBtn.enabled = NO;
            });
            timeout--;
        }
    });
    dispatch_resume(_timer);
}
- (void)setLfetImageView:(NSString *)pictureName isLeft:(BOOL ) isleft textField:(UITextField *)textField {
    textField.rightViewMode = UITextFieldViewModeAlways;
    textField.leftViewMode = UITextFieldViewModeAlways;
    UIImageView *passImageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:pictureName]];
    if (isleft) {
        textField.leftView = passImageView;
    }
    else {
        textField.rightView = passImageView;
        
    }
}
- (void)sendCode{
    
    //NSString *sendCodeUrl = [NSString stringWithFormat:@"%@%@%@%@",SSSCommomUrl,@"user/",_textFiledArray[0].text,@"/getCode"];
    
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    params[@"phone"] = [SSSUserManager getUserModel].phone;
    
    [ZDNetManager zd_requestWithType:ZDHttpRequestTypeGet UrlString:kConfigPath(kGetCode) Parameters:params SuccessBlock:^(id response) {
        
        
        if ([response[@"sataus"] intValue] == 0) {
            
            //倒计时
            [self verificationCodeOfTimer];
            [QMUITips showSucceed:@"获取验证码成功" inView:self.view hideAfterDelay:2];
            
        }else{
            
            [QMUITips showError:response[@"message"] inView:self.view hideAfterDelay:2];
            return ;
        }
        
    } FailureBlock:^(NSError *error) {
        
        [QMUITips showError:error.localizedDescription inView:self.view hideAfterDelay:2];
        
    } progress:^(int64_t bytesProgress, int64_t totalBytesProgress) {
        
        
    }];
    
}

#pragma mark - 注册按钮点击
- (void)registerBtnClick{
    
    NSString *messageNew = @"";
    if (![[self.textFiledArray[0] text] isEqualToString:@""] || [SSSRegularExpression zd_isMobileNumber:[self.textFiledArray[0] text]]) {
        messageNew = @"请输入手机号";
    }else if ([[self.textFiledArray[1] text] isEqualToString:@""]){
        
        messageNew = @"请输入验证码";
    }
    else if ([SSSRegularExpression checkPassword:[self.textFiledArray[2] text]]) {
        messageNew = @"请输入正确的密码";
    }else if ([SSSRegularExpression checkPassword:[self.textFiledArray[3] text]]){
        
        messageNew = @"请确认密码";
    }else if (![[self.textFiledArray[2] text] isEqualToString:[self.textFiledArray[3] text]]){
        
        messageNew = @"两次输入密码不一致";
    }if (![messageNew isEqualToString:@""]) {
        
        //1.校验验证码
        [self getVerificationCode];
        
    }else{
        
        
    }
}
#pragma mark - 校验验证码
- (void)getVerificationCode{
    
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    params[@"phone"] = [SSSUserManager getUserModel].phone;
    params[@"code"]  = _textFiledArray[1].text;
    
    
    // NSString *verifcationUrl = [NSString stringWithFormat:@"%@%@%@%@%@%@",SSSCommomUrl,@"user/",simple.userModel.phone,@"/",_codeTextField.text,@"/checkCode"];
    [ZDNetManager zd_requestWithType:ZDHttpRequestTypePost UrlString:kConfigPath(kVerifyCode) Parameters:params SuccessBlock:^(id response) {
        
        if ([response[@"status"] intValue] == 0) {
            
            
            [self requestData];
            
        }else{
            
            [QMUITips showError:response[@"message"] inView:self.view hideAfterDelay:2];
        }
        
    } FailureBlock:^(NSError *error) {
        
        [QMUITips showError:error.localizedDescription inView:self.view hideAfterDelay:2];
        
    } progress:^(int64_t bytesProgress, int64_t totalBytesProgress) {
        
        
    }];
    
}
//修改密码
- (void)requestData{
    
//    NSString *addBunkUrl = [NSString stringWithFormat:@"%@%@%@%@%@%@",SSSCommomUrl,@"userSecurity/",_textFiledArray[2].text,@"/",_textFiledArray[2].text,@"/findLoginPwd"];
//    // NSString *addBunkUrl = [NSString stringWithFormat:@"%@%@",SSSCommomUrl,@"userSecurity/findTransPwd"];
    NSMutableDictionary *parameter = [NSMutableDictionary dictionary];
    parameter[@"password"] = _textFiledArray[2].text;
    parameter[@"phone"] = [SSSUserManager getUserModel].phone;
    parameter[@"code"] = _textFiledArray[1].text;
    
//    [ZDNetManager zd_requestWithType:ZDHttpRequestTypePost UrlString:kConfigPath(kforgetPassword) Parameters:parameter SuccessBlock:^(id response) {
//        
//        if ([response[@"sataus"] intValue] == 0) {
//            
//            [QMUITips showSucceed:@"设置成功" inView:self.view hideAfterDelay:2];
//            [self performSelector:@selector(backSuperController) withObject:nil afterDelay:2.0f];
//        }else{
//            
//            [QMUITips showError:response[@"message"] inView:self.view hideAfterDelay:2];
//            
//            return ;
//        }
//        
//        
//    } FailureBlock:^(NSError *error) {
//        
//        [QMUITips showError:error.localizedDescription inView:self.view hideAfterDelay:2];
//    } progress:^(int64_t bytesProgress, int64_t totalBytesProgress) {
//        
//        
//    }];
    
    [[XHRequestManager manager] postRequest:kConfigPath(kforgetPassword) params:parameter success:^(id  _Nonnull responseObj) {
        
                if ([responseObj[@"sataus"] intValue] == 0) {
        
                    [QMUITips showSucceed:@"设置成功" inView:self.view hideAfterDelay:2];
                    [self performSelector:@selector(backSuperController) withObject:nil afterDelay:2.0f];
                }else{
        
                    [QMUITips showError:responseObj[@"message"] inView:self.view hideAfterDelay:2];
        
                    return ;
                }

        
    } failure:^(NSError * _Nonnull error) {
        
        [QMUITips showError:error.localizedDescription inView:self.view hideAfterDelay:2];
    }];
    
}
- (void)backSuperController{
    
    [self dismissViewControllerAnimated:YES completion:nil];
    
}

/**
 *  设置文本框的左视图
 */
- (void)setTextField:(UITextField *) textField andImageName:(NSString *) imageName{
    textField.leftViewMode = UITextFieldViewModeAlways;
    UIImageView *leftView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:imageName]];
    textField.leftView = leftView;
}
/**
 *  点击空白处，让键盘消失
 *
 *  @param touches 手指触摸的地方
 *  @param event   手指触摸
 */
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    // 让所有的文本框放弃第一响应者
    [self doResignFirstResponder];
    [self isMoveUp];
}
/**
 *  让所有的文本框放弃第一响应者的回调方法
 */
- (void)doResignFirstResponder {
    [self.textFiledArray enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        [obj resignFirstResponder];
    }];
}
#pragma mark----UITextFieldDelegate回调方法
// 文本框开始编辑的回调方法
- (void)textFieldDidBeginEditing:(UITextField *)textField {
    if (!move) {
        //        CGRect frame1 = button.frame;
        //        CGFloat y1 = frame1.origin.y;
        //        y1 -= 100;
        //        frame1.origin.y = y1;
        //        button.frame = frame1;
        NSArray *subViewsArray = self.view.subviews;
        [subViewsArray enumerateObjectsUsingBlock:^(UIView *obj, NSUInteger idx, BOOL * _Nonnull stop) {
            CGRect frame = obj.frame;
            CGFloat y = frame.origin.y;
            y -= 50;
            frame.origin.y = y;
            obj.frame = frame;
        }];
    }
    move = YES;
}

/**
 *  如果子视图已经向上移动的回调方法
 */
- (void)isMoveUp {
    if (move) {
        //        CGRect frame1 = button.frame;
        //        CGFloat y1 = frame1.origin.y;
        //        y1 += 100;
        //        frame1.origin.y = y1;
        //        button.frame = frame1;
        NSArray *subViewsArray = self.view.subviews;
        [subViewsArray enumerateObjectsUsingBlock:^(UIView *obj, NSUInteger idx, BOOL * _Nonnull stop) {
            CGRect frame = obj.frame;
            CGFloat y = frame.origin.y;
            y += 50;
            frame.origin.y = y;
            obj.frame = frame;
        }];
        move = NO;
    }
}
/**
 *  懒加载，初始化数组
 *
 *  @return 返回一个初始化好的数组
 */
- (NSMutableArray *)textFiledArray {
    if (!_textFiledArray) {
        _textFiledArray = [NSMutableArray array];
    }
    return _textFiledArray;
}
- (void)backBtn{
    
    [self dismissViewControllerAnimated:YES completion:nil];
}
@end
